﻿using System;

using System.Collections.Generic;
using System.Text;
using Silvermoon.Shapes;
using System.Drawing;
using System.IO;
using Silvermoon.Utils;
using Silvermoon.Images;


namespace Silvermoon.Controls
{
    /// <summary>
    /// Control to display a vertical scrollbar.
    /// </summary>
    public class VScrollBar : ScrollBar
    {
        public const int ScrollbarWidth = 12;

        private BackgroundShape gripper;
        private int gripHeight;
        private int gripTop;

        public VScrollBar()
            : base()
        {
            gripper = new BackgroundShape { Style = RenderStyle.Edged, Color = Color.White, Opacity = 255, Texture = SysImages.Gripper, };
            Shapes.AddLast(gripper);
            ControlFlags |= ControlFlags.CanPan;
        }

        protected override Shape Gripper
        {
            get { return gripper; }
        }

        protected override void OnSizeChanged()
        {
            if (Width != ScrollbarWidth) this.Size = ScaledSize(ScrollbarWidth, Height);
            else
            {
                Invalidate(InvalidationFlag.Appearance);
                base.OnSizeChanged();
            }
        }

        protected override void OnLayout()
        {
            CalculateGripDim();
            base.OnLayout();
        }

        private void CalculateGripDim()
        {
            int w = Width;
            int div = maximum - minimum; if (div < 1) div = 1;
            gripHeight = Height * LargeChange / div + 1;
            if (gripHeight < w) gripHeight = w;
            gripTop = Height * position / div + 1;

            w = ScrollbarWidth;
            int h = gripper.Height;
            gripper.Bounds = ScaledRect(Width - w, gripTop, w, gripHeight);
            if (h != gripHeight) gripper.Invalidate();
        }

        internal protected override void OnTouchDown(TouchEventArgs e)
        {
            HandleMouseEvent(e, e.Position);
        }


        private void HandleMouseEvent(TouchEventArgs e, Point position)
        {
            e.Handled = true;
            //Point p = e.ScreenToClient(this, position);#
            Point p = PointToClient(position);

            int w = Width;
            int div = maximum - minimum; if (div < 1) div = 1;

            int value = (p.Y - 1) * div / Height;
            if (value < minimum) value = minimum;
            int max = maximum - largeChange;
            if (value > max) value = max;
            Value = value;
        }

    }
}
